'use strict';

angular.module('com.lx.ngsl.quest.controller', [])
	/**
	 * 列表页面controller
	 */
  .controller('questListController', ['$scope', '$http', '$location', '$alert', 'questService', function($scope, $http, $location, $alert, questService) {
	$scope.items = [];
	$scope.maxSize = 5;
	$scope.pagesize = 5;
	$scope.totalItems = questService.totalItems;
	$scope.currentPage = questService.currentPage;
	$scope.searchItem = questService.searchItem;
	$scope.selectedquestId = questService.selectedquestId;

	$scope.pageChanged = function() {
		$scope.query($scope.currentPage);
	};
	
	//查询
	$scope.query = function(page) {
		page = page ? (page-1) : 0;
		$http({
			method:"GET",
			url:"/ngsl/v0/quests",
			params:{
				"page":page,
				"size":$scope.pagesize,
				"sort":"quest,asc",
				"quest":$scope.searchItem.quest,
				"type":$scope.searchItem.type
			}
		}).success(
				function(data, status) {
					$scope.items = data.content;
					$scope.totalItems = data.totalElements;
				}).error(function(data, status) {
  					alert(data.error);
					$scope.data = data || "Request failed";
					$scope.status = status;
		});
	};
	
	//新增
	$scope.add = function() {
		$location.path('/quest/add');
	}
	
	//删除
	$scope.del = function(item) {
		var id = item.id;
		$http({
			method : 'delete',
			url : '/ngsl/v0/quest/'+id,
		}).success(function(data, status) {
			$alert.tip("操作成功!");
			$scope.query($scope.currentPage);
		}).error(function(data, status) {
			alert(data.error);
			$scope.data = data || "Request failed";
			$scope.status = status;
		});
	}

	
	$scope.clear = function(){
		$scope.searchItem.quest = '';
		$scope.searchItem.type = '';
	}
	
	$scope.query($scope.currentPage);
	
  }])
	/*
	 * 新增页面controller
	 */
  .controller('questAddController', ['$scope', '$http', '$location', '$alert', 'questService', function($scope, $http, $location, $alert, questService) {
	  	$scope.submitted = false;
	  	$scope.addItem = {};
	  	$("#file_name").val('');
	  	$scope.answer = '1';
	    $scope.choices = [];
	    $scope.choice = {
	    		'questId':'',
	    		'inx':'',
	    		'content':'',
	    		'isTrue':''
	    };
	    
		$scope.submitted = false;
		$scope.getTags = function(){
			$http.get("/ngsl/v0/tags")
				.success(function(data,status){
					$scope.tags = data;
				}).error(function(data, status){
					alert(data.error);
					$scope.data = data || "Request failed";
					$scope.status = status;
				})
			
		};
		$scope.getTags();
		//选择图片后的处理
		$scope.getFile = function(id){
			var file = document.getElementById(id);
			if (!file.files || !file.files[0]) {
				 $scope.img = null;
				 $("#file_name").val('');
		            return;
		        }
		        var filesize=file.files[0].size;
		        var uploadFileName = file.value.toLowerCase().split('.');
		        //文件格式限制为JPG,JPEG,BMP
		        if(uploadFileName[1].indexOf('jpg')==-1 
		        		&& uploadFileName[1].indexOf('jpeg')==-1 
		        		&& uploadFileName[1].indexOf('bmp')==-1){
		            alert("文件格式不正确，请选择正确的文件(后缀名.jpg,.jpeg,.bmp)!");
		            $("#"+id).attr("src", "");
		            $("#file_name").val('');
		            return;
		        }
		        if(filesize>204800){
		            alert("图片大小不得超过200k");
		            $("#"+id).attr("src", "");
		            $("#file_name").val('');
		            return;
		        }
		        $scope.img = file.files[0];
		        $("#file_name").val(file.value);
		};
		//选项新增
		$scope.addChoice = function(){
			$scope.choice = {};
			$("#choiceAddModal").modal('show');
		};
		//保存选项
		$scope.saveChoice = function(){
			if(!$scope.choice.inx || !$scope.choice.content){
				$scope.errorMsg = "请填写完全后再保存！";
				return;
			}
			var exist = $scope.choices.find(item => {
				return item.inx == $scope.choice.inx
			});
			if(exist){
				$scope.errorMsg = "选项" + $scope.choice.inx + "已存在，请勿重复添加！" ;
				return;
			}else{
				$scope.errorMsg = "";
				$scope.choice.isTrue = '0';
				$scope.choices.push($scope.choice);
				$("#choiceAddModal").modal('hide');
			}
			
		};
		//删除选项
		$scope.delChoice = function(index){
			$scope.choices.splice(index,1);
		};
		// 新增保存
		$scope.save = function() {
			if ($scope.addForm.$valid) {
				var form = new FormData();
				form.append('tag', $scope.addItem.tag);
				form.append('quest', $scope.addItem.quest);
				form.append('type', $scope.addItem.type);
				form.append('choices', JSON.stringify($scope.choices));
				form.append('img', $scope.img);
				if($scope.addItem.type == '判断题'){
					form.append('answer',$scope.answer);
				}
				$http({
					method : 'post',
					url : '/ngsl/v0/quest',
					data : form,
					headers: {'Content-Type': undefined},
					transformRequest: angular.identity//序列化
				}).success(
						function(data, status) {
							if(data == false){
								$alert.error({message:"保存失败！"});
							}else{
								$alert.tip("操作成功!");
								$scope.backToList();
							}
						}).error(function(data, status) {
		  					alert(data.error);
							$scope.data = data || "Request failed";
							$scope.status = status;
				});
			} else {
				$scope.submitted = true;
			}
		}
		
		$scope.backToList = function() {
			$location.path('/quest/list');
		};
		
  }])
 
  	







